package wechat.httpRequest;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import wechat.entities.CgiAccessTokenResult;
import wechat.entities.CgiTicketResult;

import java.util.LinkedHashMap;
import java.util.Map;

public class WechatCgiHttpRequest {

    private static final String tokenUri = "https://api.weixin.qq.com/cgi-bin/token";

    private  static final String  ticketUri = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

    private static RestTemplate restTemplate = new RestTemplate();
    private static Logger log = LoggerFactory.getLogger(WechatCgiHttpRequest.class);
    /****
     * 获取全局token  两小时内有效 必须缓存在服务器
     * @param grant_type  "client_credential"
     * @param appid  公众号id
     * @param secret  秘钥
     */
    public static CgiAccessTokenResult getToken(String grant_type, String appid, String  secret){
        Map<String, Object> param = new LinkedHashMap(4);
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("grant_type", grant_type);
        String url = WechatOath2HttpRequest.getUrl(tokenUri, param, "获取微信全局token");
        String result = restTemplate.getForObject(url, String.class);
        /**
         * succeess：   {"access_token":"ACCESS_TOKEN","expires_in":7200}
         * FAIL： {"errcode":40013,"errmsg":"invalid appid"}
         */
        log.info("请求微信全局access_token刷新返回--" + result);
        CgiAccessTokenResult accessToken = JSONObject.parseObject(result, CgiAccessTokenResult.class);
        if (StringUtils.isEmpty(accessToken.getErrcode())) {
            accessToken.setCode(200);
        } else {
            accessToken.setCode(accessToken.getErrcode());
        }
        return accessToken;
    }

    /***
     * 调用微信JS接口的临时票据  两小时内有效   必须缓存在服务器
     * @param accessToke 全局token
     */
    public static CgiTicketResult getTicket(String accessToke){
        //access_token=ACCESS_TOKEN&type=jsapi
        Map<String, Object> param = new LinkedHashMap(4);
        param.put("access_token", accessToke);
        param.put("type", "jsapi");
        String url = WechatOath2HttpRequest.getUrl(ticketUri, param, "调用微信JS接口的临时票据");
        String result = restTemplate.getForObject(url, String.class);
        /***
         * {
         * "errcode":0,
         * "errmsg":"ok",
         * "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
         * "expires_in":7200
         * }
         */
        log.info("请求微信ticket刷新返回--" + result);
        CgiTicketResult  ticket = JSONObject.parseObject(result, CgiTicketResult.class);
        if (0 == ticket.getErrcode()){
            ticket.setCode(200);
        }else{
            ticket.setCode(ticket.getErrcode());
        }
        return ticket;
    }



}
